package me.ree.zkproduct.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ApplicationContextHandler implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext context;

    @Override
    public void destroy() throws Exception {
        log.info("DisposableBean destroy begin...");
        context = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("ApplicationContextHandler setApplicationContext begin, applicationContext={}", applicationContext);
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static boolean isLoadedClass(String className) {
        return context.containsBean(className);
    }

    public static <T> T getBean(String className) {
        if (context.containsBean(className)) {
            return (T) context.getBean(className);
        }
        return null;
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
}
